如果实现一个高性能的 CSS 动画效果?
尽可能使用 CSS3 过渡和动画
transition+transfrom
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s, height 2s, transform 2s;
}
div:hover {
width: 200px;
height: 200px;
transform: rotate(180deg);
}
@keyframes[kiː freɪmz]
+ animation
div {
width: 100px;
height: 100px;
background: red;
}
div:hover {
animation: mystyle 2s;
}
@keyframes mystyle {
0% {
width: 100px;
}
50% {
width: 200px;
}
100% {
width: 100px;
}
}
如果用 js,尽量使用requestAnimationFrame
requestAnimationFrame:传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行
const element = document.getElementById('app')
let start
function step(timestamp) {
if (start === undefined)
start = timestamp;//声明时间戳
const elapsed = timestamp - start;
//这里使用`Math.min()`确保元素刚好停在200px的位置。
element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';
if (elapsed < 2000) { // 在两秒后停止动画
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
预览链接:http://js.jirengu.com/limepowosi/1/watch?html,js,output
timeStamp:返回事件发生时的时间戳 预览链接:http://js.jirengu.com/xujicaseci/1/watch?html,js,output